package com.sakura.hk.sakura.springboot.plugin.task;

import com.sakura.hk.sakura.springboot.plugin.SakuraBootType;
import com.sakura.hk.sakura.springboot.plugin.SakuraExtension;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.internal.AbstractTask;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 解压缩Springboot构建,输出到缓存目录
 *
 * @Author: 贺坤
 * @Date: 2021/7/13 13:53
 */
public class DecompressionSpringbootBuild extends DefaultTask {
    /**
     * 当前任务名称
     */
    public static final String MY_TASK_NAME = "decompressionSpringbootBuild";
    /**
     * 缓存目录
     */
    private File cacheDir;
    /**
     * 缓存目录名称
     */
    private String cacheName;
    /**
     * 构建目录
     */
    private File buildDir;
    /**
     * 构建jar名称
     */
    private String buildJarName;
    /**
     * 打包类型
     */
    private SakuraBootType type ;

    @TaskAction
    public void action() {
        init();
        // 原始jar包文件
        File buildFile = new File(buildDir,buildJarName+"."+type.getValue());
        // 检查缓存目录是否存在
        File cacheFile = new File(cacheDir,cacheName);
        if (!cacheFile.exists()){
            cacheFile.mkdirs();
        }
        getProject().copy((copy) -> {
            copy.from(getProject().zipTree(buildFile));
            copy.into(cacheFile);
        });
    }

    public static AbstractTask foundMyTask(Project project) {
        DefaultTask task = project.getTasks().create(MY_TASK_NAME, DecompressionSpringbootBuild.class);
        task.setDescription("解压springboot生成的jar包");
        task.dependsOn(SakuraInit.MY_TASK_NAME);
        return task;
    }

    private void init() {
        SakuraExtension sakuraExtension = getProject().getExtensions().getByType(SakuraExtension.class);
        this.cacheDir = sakuraExtension.getCacheDir();
        this.cacheName = sakuraExtension.getCacheName();
        this.buildDir = sakuraExtension.getBuildDir();
        this.buildJarName = sakuraExtension.getBuildJarName();
        this.type = sakuraExtension.getType();
    }
}
